﻿using Aliyun.OSS;
using Aliyun.OSS.Common;
using Dapper;
using FreeRedis;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using WhiteBoardServerNET.Entity;
using WhiteBoardServerNET.Models;
using static Slapper.AutoMapper;

namespace WhiteBoardServerNET.Controllers
{
    [RoutePrefix("api/liveinfo")]
    public class LiveInfoController : ApiController
    {
        //private readonly string[] _allowedExtensions = { ".doc", ".docx", ".ppt", ".pptx", ".jpg", ".png", ".pdf" };
        private readonly string[] _allowedExtensions = { ".ppt", ".pptx", ".jpg", ".png", ".pdf" };

        private readonly string alioss_endpoint = null;
        private readonly string alioss_region = null;
        private readonly string alioss_accessKeyId = null;
        private readonly string alioss_accessKeySecret = null;
        private readonly string alioss_bucketName = null;
        private readonly string alioss_prefixPath = null;
        private readonly string live_event_callback = null;
        private readonly string write_errorlog = null;
        private readonly string write_systemlog = null;
        private readonly string redisConf = null;

        //    private readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string>
        //{
        //    { ".jpg", "image/jpeg" },
        //    { ".png", "image/png" },
        //    { ".pdf", "application/pdf" },
        //    { ".ppt", "application/msword" },
        //    { ".pptx", "application/msword" },
        //    { ".doc", "application/msword" },
        //    { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }
        //};
        private readonly string _conn = null;
        // redis
        public static RedisClient _redis = null;
        public LiveInfoController()
        {
            if (_conn == null)
            {
                _conn = ConfigurationManager.AppSettings["QyhWhiteboardDb"];
            }
            if (alioss_endpoint == null)
            {
                alioss_endpoint = ConfigurationManager.AppSettings["alioss_endpoint"];
                alioss_region = ConfigurationManager.AppSettings["alioss_region"];
                alioss_accessKeyId = ConfigurationManager.AppSettings["alioss_accessKeyId"];
                alioss_accessKeySecret = ConfigurationManager.AppSettings["alioss_accessKeySecret"];
                alioss_bucketName = ConfigurationManager.AppSettings["alioss_bucketName"];
                alioss_prefixPath = ConfigurationManager.AppSettings["alioss_prefixPath"];
                live_event_callback = ConfigurationManager.AppSettings["live_event_callback"];
                write_errorlog = ConfigurationManager.AppSettings["write_errorlog"];
                write_systemlog = ConfigurationManager.AppSettings["write_systemlog"];
                redisConf = ConfigurationManager.AppSettings["RedisConf"];
            }

            if (_redis == null)
            {
                _redis = new RedisClient(redisConf);


                try
                {
                    _redis.Get($"ynxp.fun");
                }
                catch (Exception ex)
                {
                    WriteErrLog($"[redis 访问失败{ex.Message}]");
                }
            }
        }

        /// <summary>
        /// 保存页面数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("save")]
        public object saveIdxContent()
        {
            savePageDataModel _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<savePageDataModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (string.IsNullOrWhiteSpace(_param.id) || _param.idx <= 0 || string.IsNullOrWhiteSpace(_param.json) || string.IsNullOrWhiteSpace(_param.table))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }

                //数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        var id_idx = conn.Query<long>($"select id from room_whiteboardhistory_{_param.table} where cid = @cid and idx = @idx", new { cid = _param.id, idx = _param.idx }, commandType: CommandType.Text).FirstOrDefault();
                        if (id_idx <= 0)
                        {
                            if (conn.Execute($"insert into room_whiteboardhistory_{_param.table} (cid,idx,json,md5)values(@cid,@idx,@json,@md5)", new { cid = _param.id, idx = _param.idx, json = _param.json, md5 = _param.md5 }, commandType: CommandType.Text) > 0)
                            {

                            }
                        }
                        else
                        {
                            if (conn.Execute($"update room_whiteboardhistory_{_param.table} set json = @json,md5 = @md5 where id = @id_idx", new { id_idx = id_idx, json = _param.json, md5 = _param.md5 }, commandType: CommandType.Text) > 0)
                            {

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/save, error : {ex.Message}");
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                WriteErrLog($"请求异常 /api/liveinfo/save, error : {ex.Message}");
                return Ok(new {
                    Code = 500,
                    Msg = ex.Message
                });
            }

            return Ok(new {
                Code = 200
            });
        }

        /// <summary>
        /// 获取页面数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("getcontent")]
        public object getIdxContent()
        {
            getPageDataModel _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<getPageDataModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (string.IsNullOrWhiteSpace(_param.id) || _param.idx <= 0 || string.IsNullOrWhiteSpace(_param.table))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }

                //数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        var res = conn.Query<getPageDataOutModel>($"select json,md5 from room_whiteboardhistory_{_param.table} where cid = @cid and idx = @idx", new { cid = _param.id, idx = _param.idx }, commandType: CommandType.Text).FirstOrDefault();
                        return Ok(new {
                            Code = 200,
                            Data = res
                        });
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/getcontent, error : {ex.Message}");
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                WriteErrLog($"请求异常 /api/liveinfo/getcontent, error : {ex.Message}");
                return Ok(new {
                    Code = 500,
                    Msg = ex.Message
                });
            }

            return Ok(new {
                Code = 500
            });
        }

        /// <summary>
        /// 添加用户授权信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("upinfo")]
        public object AddAuthInfo()
        {
            authModel _param = null;
            string guid = $"{Guid.NewGuid().ToString("N").Substring(0, 8)}_{DateTime.Now.Millisecond}";
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<authModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (string.IsNullOrWhiteSpace(_param.userid) || string.IsNullOrWhiteSpace(_param.token) || string.IsNullOrWhiteSpace(_param.name))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }

                //数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        var authinfo = conn.Query<RoomAuth>("select * from room_auth where userid = @userid", new { userid = _param.userid }, commandType: CommandType.Text).FirstOrDefault();
                        if (authinfo == null)
                        {
                            if (conn.Execute($"insert into room_auth (userid,tk,add_time,uuid,name)values(@userid,@tk,'{DateTime.Now.ToString("yyyy-MM-dd HH:MM:ss")}','${guid}',@name)", new { tk = _param.token, userid = _param.userid, name = _param.name }, commandType: CommandType.Text) > 0)
                            {

                            }
                        }
                        else
                        {
                            if (conn.Execute($"update room_auth set tk = @tk , add_time = '{DateTime.Now.ToString("yyyy-MM-dd HH:MM:ss")}',uuid = '{guid}',name = @name where userid = @userid ", new { tk = _param.token, userid = _param.userid, name = _param.name }, commandType: CommandType.Text) > 0)
                            {

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/upinfo, error : {ex.Message}");
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception)
            {
                return Ok(new {
                    Code = 500,
                    Msg = "参数异常【get body error】"
                });
            }

            return Ok(new {
                Code = 200,
                Data = guid
            });
        }

        /// <summary>
        /// 验证授权
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ver")]
        public object VerAuth()
        {
            authModel _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<authModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (string.IsNullOrWhiteSpace(_param.userid) || string.IsNullOrWhiteSpace(_param.token))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }

                //数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        var authinfo = conn.Query<RoomAuth>("select * from room_auth where userid = @userid", new { userid = _param.userid }, commandType: CommandType.Text).FirstOrDefault();
                        if (authinfo == null)
                        {
                            // 尚未登录
                            return Ok(new {
                                Code = 2001
                            });
                        }
                        if (authinfo.tk != _param.token)
                        {
                            // 被挤下线
                            return Ok(new {
                                Code = 1001
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/ver, error : {ex.Message}");
                    }
                    finally
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new {
                    Code = 500,
                    Msg = ex.Message
                });
            }

            return Ok(new {
                Code = 200
            });
        }

        /// <summary>
        /// 获取回放信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("callback")]
        public async Task<object> liveCallBack()
        {
            liveCallBack _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 写入日志
                WriteCallbackLog($"接收到阿里云录制事件回调: {jsonContent}");
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<liveCallBack>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500
                    });
                }
                int status = -1;
                if (_param.duration > 0)
                {
                    // 记录数据
                    // 数据库
                    using (MySqlConnection conn = new MySqlConnection(_conn))
                    {
                        try
                        {
                            if (conn.State != ConnectionState.Open)
                            {
                                conn.Open();
                            }
                            if (conn.Execute(
                                $"insert into room_repeat (liveid,duration,start_time,stop_time,file_url,record_id,uri)values(@liveid,{_param.duration},{_param.start_time},{_param.stop_time},@file_url,@record_id,@uri)",
                                new {
                                    liveid = _param.stream,
                                    file_url = _param.file_url,
                                    record_id = _param.record_id,
                                    uri = _param.uri
                                },
                                commandType: CommandType.Text
                                ) > 0)
                            {

                            }
                            //查询直播状态 教室状态 0 未开播 1 直播中 2 已结束
                            status = conn.Query<int>("select status from room_infos where id = @cid", new { cid = _param.stream }, commandType: CommandType.Text).FirstOrDefault();
                        }
                        catch (Exception ex)
                        {
                            WriteErrLog($"请求异常 /api/liveinfo/callback, error : {ex.Message}");
                        }
                    }
                    ////查询
                    //if (status == 2)
                    //{
                    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(_param.start_time);
                    DateTime localTime = dateTimeOffset.LocalDateTime;
                    // 格式化为字符串
                    string start_time = localTime.ToString("yyyy-MM-dd HH:mm:ss");
                    DateTimeOffset dateTimeOffset1 = DateTimeOffset.FromUnixTimeSeconds(_param.stop_time);
                    DateTime localTime1 = dateTimeOffset1.LocalDateTime;
                    // 格式化为字符串
                    string stop_time = localTime1.ToString("yyyy-MM-dd HH:mm:ss");
                    string url = $"{live_event_callback}&id={_param.stream}&time={_param.duration}&st={start_time}&et={stop_time}&url={_param.file_url}";
                    // 写入日志
                    WriteCallbackLog($"开始推送业务数据: {url}");
                    //直播间已结束，发送回调
                    using (var client = new HttpClient())
                    {
                        try
                        {
                            // 发送GET请求
                            HttpResponseMessage response = await client.GetAsync(url);
                            // 确保响应成功（状态码200-299）
                            response.EnsureSuccessStatusCode();
                            // 读取响应内容（字符串形式）
                            string responseBody = await response.Content.ReadAsStringAsync();
                            // 处理异常
                            PushWriteLog(_param.stream, 1, url, $"推送业务数据成功 StatusCode: {response.StatusCode} Result：{responseBody}");
                        }
                        catch (HttpRequestException ex)
                        {
                            // 处理异常
                            PushWriteLog(_param.stream, 0, url, $"推送业务数据失败，Error: {ex.Message} url：{url}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteErrLog($"请求异常 /api/liveinfo/callback, error : {ex.Message}");
                return Ok(new {
                    Code = 500
                });
            }


            return Ok(new {
                Code = 200,
                Msg = "Success"
            });
        }

        /// <summary>
        /// 获取直播-回访列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("getrepeat")]
        public object getLiveRepeat()
        {
            liveRepeat _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<liveRepeat>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500
                    });
                }
                if (!string.IsNullOrEmpty(_param.id))
                {
                    // 记录数据
                    // 数据库
                    List<liveRepeatOut> list = null;
                    using (MySqlConnection conn = new MySqlConnection(_conn))
                    {
                        try
                        {
                            if (conn.State != ConnectionState.Open)
                            {
                                conn.Open();
                            }
                            //查询直播状态 教室状态 0 未开播 1 直播中 2 已结束
                            list = conn.Query<liveRepeatOut>("select id,file_url from room_repeat where liveid = @cid", new { cid = _param.id }, commandType: CommandType.Text).ToList();
                        }
                        catch (Exception)
                        {

                        }
                        finally
                        {

                        }
                    }
                    return Ok(new {
                        Code = 200,
                        Data = list
                    });
                }
            }
            catch (Exception ex)
            {
                WriteErrLog($"请求异常 /api/liveinfo/getrepeat, error : {ex.Message}");
                return Ok(new {
                    Code = 500
                });
            }
            return Ok(new {
                Code = 500
            });
        }

        /// <summary>
        /// 清空课件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("clear")]
        public object clear()
        {
            clearModel _param = null;
            try
            { // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<clearModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }
                if (string.IsNullOrWhiteSpace(_param.id) || string.IsNullOrWhiteSpace(_param.table))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get idx len error】"
                    });
                }
                bool res = false;
                RoomSources _info = null;
                //查询数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        _info = conn.Query<RoomSources>("select * from room_sources where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text).FirstOrDefault();
                        if (conn.Execute($"update room_sources set pages =''  where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text) > 0)
                        {
                            res = true;
                        }
                        if (conn.Execute($"delete from room_whiteboardhistory_{_param.table}  where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text) > 0)
                        {
                            res = true;
                        }
                        if (conn.Execute($"delete from file_tasks  where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text) > 0)
                        {
                            res = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/clear, error : {ex.Message}");
                        res = false;
                    }
                    finally
                    {

                    }
                }
                // 删除OSS文件
                // 创建ClientConfiguration实例，按照您的需要修改默认参数。
                var conf = new ClientConfiguration();
                // 设置v4签名。
                conf.SignatureVersion = SignatureVersion.V4;
                // 创建OssClient实例。
                var client = new OssClient(alioss_endpoint, alioss_accessKeyId, alioss_accessKeySecret, conf);
                // 设置Region
                client.SetRegion(alioss_region);
                // 设置前缀
                string prefix = string.Empty;
                if (!string.IsNullOrEmpty(alioss_prefixPath) && !string.IsNullOrWhiteSpace(alioss_prefixPath))
                {
                    prefix = $"{alioss_prefixPath}/";
                }
                try
                {
                    if (!string.IsNullOrWhiteSpace(_info.pages))
                    {
                        var _ids = JsonConvert.DeserializeObject<List<int>>($"[{_info.pages}]");
                        List<string> list = new List<string>();
                        for (int i = 0; i < _ids.Count; i++)
                        {
                            // 上传文件。
                            list.Add($"{prefix}{_param.id}/{_ids[i]}.jpg");
                        }
                        var result = client.DeleteObjects(new DeleteObjectsRequest(alioss_bucketName, list));
                    }
                }
                catch (Exception ex)
                {
                    WriteErrLog($"请求异常 /api/liveinfo/clear, error : {ex.Message}");
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }
                return Ok(new {
                    Code = 200
                });
            }
            catch (Exception)
            {
                return Ok(new {
                    Code = 500,
                    Msg = "参数异常"
                });
            }
        }

        /// <summary>
        /// 删除课件中的图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("delete")]
        public object delete()
        {
            deleteModel _param = null;
            try
            { // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<deleteModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }
                if (string.IsNullOrWhiteSpace(_param.id) || string.IsNullOrWhiteSpace(_param.table))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }
                if (_param.idx <= 0)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }
                bool res = false;
                RoomSources _info = null;
                //查询数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        _info = conn.Query<RoomSources>("select * from room_sources where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text).FirstOrDefault();
                        if (string.IsNullOrWhiteSpace(_info?.pages))
                        {

                        }
                        else
                        {
                            string newpages = string.Empty;
                            if (!string.IsNullOrWhiteSpace(_info.pages))
                            {
                                var _ids = JsonConvert.DeserializeObject<List<int>>($"[{_info.pages}]");
                                _ids = _ids.Where(x => x != _param.idx).ToList();
                                if (_ids.Count > 0)
                                {
                                    newpages = string.Join(",", _ids);
                                }
                                else
                                {
                                    newpages = "";
                                }
                            }
                            if (conn.Execute($"update room_sources set pages = @pages  where cid = @cid", new { cid = _param.id, pages = newpages }, commandType: CommandType.Text) > 0)
                            {
                                res = true;
                            }
                            if (conn.Execute($"delete from room_whiteboardhistory_{_param.table} where cid = @cid and idx = @idx", new { cid = _param.id, idx = _param.idx }, commandType: CommandType.Text) > 0)
                            {
                                res = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/delete, error : {ex.Message}");
                        res = false;
                    }
                    finally
                    {

                    }
                }
                // 删除OSS文件
                // 创建ClientConfiguration实例，按照您的需要修改默认参数。
                var conf = new ClientConfiguration();
                // 设置v4签名。
                conf.SignatureVersion = SignatureVersion.V4;
                // 创建OssClient实例。
                var client = new OssClient(alioss_endpoint, alioss_accessKeyId, alioss_accessKeySecret, conf);
                // 设置Region
                client.SetRegion(alioss_region);
                // 设置前缀
                string prefix = string.Empty;
                if (!string.IsNullOrEmpty(alioss_prefixPath) && !string.IsNullOrWhiteSpace(alioss_prefixPath))
                {
                    prefix = $"{alioss_prefixPath}/";
                }
                try
                {
                    var result = client.DeleteObject(alioss_bucketName, $"{prefix}{_param.id}/{_param.idx}.jpg");
                }
                catch (Exception ex)
                {
                    WriteErrLog($"请求异常 /api/liveinfo/delete, error : {ex.Message}");
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常"
                    });
                }
                return Ok(new {
                    Code = 200
                });
            }
            catch (Exception)
            {
                return Ok(new {
                    Code = 500,
                    Msg = "参数异常"
                });
            }
        }

        /// <summary>
        /// 单个文件获取OSS url
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("osssingleurl")]
        public object ossSingleurl()
        {
            liveRepeat _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<liveRepeat>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (!string.IsNullOrWhiteSpace(_param.id))
                {
                    // 创建ClientConfiguration实例，按照您的需要修改默认参数。
                    var conf = new ClientConfiguration();
                    // 设置v4签名。
                    conf.SignatureVersion = SignatureVersion.V4;
                    // 创建OssClient实例。
                    var client = new OssClient(alioss_endpoint, alioss_accessKeyId, alioss_accessKeySecret, conf);
                    // 设置Region
                    client.SetRegion(alioss_region);
                    // 设置前缀
                    string prefix = string.Empty;
                    if (!string.IsNullOrEmpty(alioss_prefixPath) && !string.IsNullOrWhiteSpace(alioss_prefixPath))
                    {
                        prefix = $"{alioss_prefixPath}/";
                    }
                    try
                    {
                        string uri = string.Empty;
                        // 数据库
                        using (MySqlConnection conn = new MySqlConnection(_conn))
                        {
                            try
                            {
                                if (conn.State != ConnectionState.Open)
                                {
                                    conn.Open();
                                }
                                uri = conn.Query<string>("select uri from room_repeat where liveid = @cid", new { cid = _param.id }, commandType: CommandType.Text).FirstOrDefault();
                            }
                            catch (Exception)
                            {

                            }
                            finally
                            {

                            }
                        }
                        if (!string.IsNullOrWhiteSpace(uri))
                        {
                            // 生成预签名URL。
                            var generatePresignedUriRequest = new GeneratePresignedUriRequest(alioss_bucketName, uri, SignHttpMethod.Get)
                            {
                                Expiration = DateTime.Now.AddHours(12),
                            };
                            var Uri = client.GeneratePresignedUri(generatePresignedUriRequest).ToString();
                            Uri = Uri.Replace("http://qyhlive-test.oss-cn-shenzhen.aliyuncs.com", "https://liveoss.ynxp.fun");
                            return Ok(new {
                                Code = 200,
                                Data = Uri
                            });
                        }
                    }
                    catch (OssException ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/ossSingleurl, error : {ex.Message}");
                        return Ok(new {
                            Code = 500,
                            Msg = ex.Message
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                return Ok(new {
                    Code = 500,
                    Msg = ex.Message
                });
            }
            return Ok(new {
                Code = 500,
            });
        }

        /// <summary>
        /// 批量获取OSS url
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ossurl")]
        public object ossurl()
        {
            paramModel _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<paramModel>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get body error】"
                    });
                }

                if (_param.idx?.Count > 30)
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数异常【get idx len error】"
                    });
                }
            }
            catch (Exception)
            {
                return Ok(new {
                    Code = 500,
                    Msg = "参数异常【get body error】"
                });
            }
            // 创建ClientConfiguration实例，按照您的需要修改默认参数。
            var conf = new ClientConfiguration();
            // 设置v4签名。
            conf.SignatureVersion = SignatureVersion.V4;
            // 创建OssClient实例。
            var client = new OssClient(alioss_endpoint, alioss_accessKeyId, alioss_accessKeySecret, conf);
            // 设置Region
            client.SetRegion(alioss_region);
            // 设置前缀
            string prefix = string.Empty;
            if (!string.IsNullOrEmpty(alioss_prefixPath) && !string.IsNullOrWhiteSpace(alioss_prefixPath))
            {
                prefix = $"{alioss_prefixPath}/";
            }
            List<urlModel> urls = new List<urlModel>();
            try
            {
                for (int i = 0; i < _param.idx.Count; i++)
                {
                    // 生成预签名URL。
                    var generatePresignedUriRequest = new GeneratePresignedUriRequest(alioss_bucketName, $"{prefix}{_param.id}/{_param.idx[i]}.jpg", SignHttpMethod.Get)
                    {
                        Expiration = DateTime.Now.AddHours(12),
                    };
                    urls.Add(new urlModel()
                    {
                        id = _param.idx[i],
                        url = client.GeneratePresignedUri(generatePresignedUriRequest).ToString()
                    });
                }
            }
            catch (OssException ex)
            {
                WriteErrLog($"请求异常 /api/liveinfo/ossurl, error : {ex.Message}");
            }

            return Ok(new {
                Code = 200,
                Data = urls
            });
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("upfile")]
        public async Task<object> upfile()
        {
            // 检查请求是否包含multipart/form-data内容
            if (!Request.Content.IsMimeMultipartContent())
            {
                return Ok(new {
                    Code = 500,
                    Msg = "请求必须包含multipart/form-data内容"
                });
            }
            string filePath = string.Empty;
            string converPath = string.Empty;
            string id = string.Empty;
            try
            {
                Request.Headers.TryGetValues("id", out var id1);
                RoomSources _info = null;
                id = id1?.Count() > 0 ? id1.FirstOrDefault() : "";
                if (string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(id))
                {
                    return Ok(new {
                        Code = 500,
                        Msg = "参数错误"
                    });
                }
                // 设置上传目录
                var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
                // 如果目录不存在则创建
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                // 创建流提供程序
                var provider = new MultipartFormDataStreamProvider(uploadPath);
                // 读取内容
                var files = await Request.Content.ReadAsMultipartAsync(provider);
                // 上传文件列表
                List<string> filesurl = new List<string>();
                // 读取文件流
                foreach (var item in provider.FileData)
                {
                    // 获取第一个文件
                    var fileData = provider.FileData.FirstOrDefault();
                    if (fileData == null)
                    {
                        continue;
                    }
                    // 获取原始文件名
                    var fileName = fileData.Headers.ContentDisposition.FileName.Trim('\"');
                    var fileExtension = Path.GetExtension(fileName).ToLower();
                    // 验证文件扩展名
                    if (!_allowedExtensions.Contains(fileExtension))
                    {
                        File.Delete(fileData.LocalFileName);
                        continue;
                    }
                    // 生成新文件名（避免重名）
                    var newFileName = $"{Guid.NewGuid()}{Path.GetExtension(fileName)}";
                    // 源文件
                    filePath = Path.Combine(uploadPath, newFileName);
                    // 重命名文件
                    File.Move(fileData.LocalFileName, filePath);
                    //添加到文件列表
                    filesurl.Add(filePath);
                }

                //查询数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        _info = conn.Query<RoomSources>("select * from room_sources where cid = @cid", new { cid = id }, commandType: CommandType.Text).FirstOrDefault();
                        if (_info == null)
                        {
                            if (conn.Execute($"insert into room_sources (cid,pages,uploading,uptime,`table`)values(@cid,'',1,now(),@table)", new {
                                cid = id,
                                table = DateTime.Now.ToString("yyyyMM")
                            }, commandType: CommandType.Text) > 0)
                            {
                            }
                        }
                        else
                        {
                            if (conn.Execute($"update room_sources set uploading = 1,uptime=now() where cid = @cid", new { cid = id }, commandType: CommandType.Text) > 0)
                            {

                            }
                        }
                        if (conn.Execute($"insert into file_tasks (files,state,cid,create_time)values(@files,0,@cid,now())", new {
                            files = string.Join("|", filesurl),
                            cid = id
                        }, commandType: CommandType.Text) > 0)
                        {

                        }

                        // 加入缓存
                        _redis.Set($"sources:{id}", 1, 3600);
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/upfile, error : {ex.Message}");
                    }
                }
                return Ok(new {
                    Code = 200
                });
            }
            catch (Exception ex)
            {
                return Ok(new {
                    Code = 500,
                    Msg = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object Get(string id)
        {
            // 检查请求是否包含multipart/form-data内容
            if (string.IsNullOrWhiteSpace(id) || string.IsNullOrEmpty(id))
            {
                return BadRequest("参数错误");
            }
            RoomSources _info = null;
            //查询数据库
            using (MySqlConnection conn = new MySqlConnection(_conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    var liveid = conn.Query<string>("select id from room_infos where id = @cid", new { cid = id }, commandType: CommandType.Text).FirstOrDefault();
                    if (!string.IsNullOrWhiteSpace(liveid))
                    {
                        _info = conn.Query<RoomSources>("select * from room_sources where cid = @cid", new { cid = id }, commandType: CommandType.Text).FirstOrDefault();
                        if (_info != null)
                        {
                            if ((DateTime.Now - _info?.uptime)?.TotalSeconds > 1800)
                            {
                                if (conn.Execute($"update room_sources set uploading=0,uptime=null where id = @id", new { id = _info.id }, commandType: CommandType.Text) > 0)
                                {

                                }
                                _info.uploading = 0;
                            }
                        }
                        return Ok(new {
                            Code = 200,
                            Data = _info == null ? new RoomSources()
                            {
                                cid = id,
                            } : _info
                        });
                    }
                }
                catch (Exception ex)
                {
                    WriteErrLog($"请求异常 /api/liveinfo/{id},error : {ex.Message}");
                }
                finally
                {

                }
            }

            return Ok(new {
                Code = 500,
                Data = _info
            });
        }

        /// <summary>
        /// 查询状态 -1 系统异常 1 处理中... 0 处理完成
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("state")]
        public int GetState()
        {
            getStateParam _param = null;
            try
            {
                // 1. 读取请求体
                var jsonContent = Request.Content.ReadAsStringAsync().Result;
                // 2. 定义接收模型
                _param = JsonConvert.DeserializeObject<getStateParam>(jsonContent);
                // 3. 参数验证
                if (_param == null)
                {
                    return -1;
                }

                if (string.IsNullOrWhiteSpace(_param.id))
                {
                    return -1;
                }
            }
            catch (Exception)
            {
                return -1;
            }

            string _uploading = _redis.Get($"sources:{_param.id}");

            if (string.IsNullOrWhiteSpace(_uploading) || string.IsNullOrEmpty(_uploading))
            {
                //查询数据库
                using (MySqlConnection conn = new MySqlConnection(_conn))
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                        {
                            conn.Open();
                        }
                        var stateres = conn.Query<stateOutModel>($"select uploading from room_sources where cid = @cid", new { cid = _param.id }, commandType: CommandType.Text)?.FirstOrDefault();
                        var _retval = stateres?.id > 0 ? stateres.uploading : -1;
                        _redis.Set($"sources:{_param.id}", _retval, 3600);
                        return _retval;
                    }
                    catch (Exception ex)
                    {
                        WriteErrLog($"请求异常 /api/liveinfo/state,error : {ex.Message}");
                    }
                    finally
                    {

                    }
                }
            }
            else
            {
                if (int.TryParse(_uploading, out int cache_uploading))
                {
                    return cache_uploading;
                }
                return -1;
            }
            return -1;
        }

        #region 工具方法Tool


        /// <summary>
        /// 错误日志写入
        /// </summary>
        /// <param name="strErrCode"></param>
        public void WriteErrLog(string strErrCode)
        {
            if (write_errorlog != "1") return;
            // 设置上传目录
            var uploadPath = HttpContext.Current.Server.MapPath("~/Logs");
            // 如果目录不存在则创建
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            string strFileName = uploadPath + "\\ErrorLog" + System.DateTime.Now.ToString("yyyyMMdd") + ".txt";

            StreamWriter sw = File.AppendText(strFileName);
            try
            {
                sw.WriteLine(System.DateTime.Now.ToString() + "," + strErrCode);
                sw.Flush();
            }
            catch
            {
                return;
            }
            finally
            {
                sw.Close();
            }
        }

        /// <summary>
        /// 阿里云callback日志
        /// </summary>
        /// <param name="strErrCode"></param>
        public void WriteCallbackLog(string json)
        {
            if (write_systemlog != "1") return;
            //数据库
            using (MySqlConnection conn = new MySqlConnection(_conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    if (conn.Execute($"insert into alicallback_info (json,create_time)values(@json,now())", new { json = json }, commandType: CommandType.Text) > 0)
                    {
                    }
                }
                catch (Exception ex)
                {
                    WriteErrLog($"写入阿里云回调日志失败，error:{ex.Message} data:{json}");
                }
            }
        }

        /// <summary>
        /// 推送日志
        /// </summary>
        /// <param name="strErrCode"></param>
        public void PushWriteLog(string id, int state, string url, string msg)
        {
            //if (write_systemlog != "1") return;
            //// 设置上传目录
            //var uploadPath = HttpContext.Current.Server.MapPath("~/Logs");
            //// 如果目录不存在则创建
            //if (!Directory.Exists(uploadPath))
            //{
            //    Directory.CreateDirectory(uploadPath);
            //}
            //string strFileName = uploadPath + "\\SystemLog" + System.DateTime.Now.ToString("yyyyMMdd") + ".txt";

            //StreamWriter sw = File.AppendText(strFileName);
            //try
            //{
            //    sw.WriteLine(System.DateTime.Now.ToString() + "," + strErrCode);
            //    sw.Flush();
            //}
            //catch
            //{
            //    return;
            //}
            //finally
            //{
            //    sw.Close();
            //}

            //数据库
            using (MySqlConnection conn = new MySqlConnection(_conn))
            {
                try
                {
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    if (conn.Execute($"insert into push_liveinfo (cid,state,url,msg,create_time)values(@cid,@state,@url,@msg,now())", new {
                        cid = id,
                        state = state,
                        url = url,
                        msg = msg
                    }, commandType: CommandType.Text) > 0)
                    {
                    }
                }
                catch (Exception ex)
                {
                    WriteErrLog($"写入推送日志失败，error:{ex.Message} id:{id} state:{state} url:{url} msg:{msg}");
                }
                finally
                {

                }
            }
        }
        #endregion
    }
}
